﻿using System;
using System.Data.Services.Client;
using System.Diagnostics;
using System.Linq;
using Azure.Toolkit;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using SimplePoll.Web.Models;

namespace SimplePoll.Web.DataAccess
{
    public class PollAnswerRepository
    {
        readonly CloudStorageAccount account;

        public PollAnswerRepository()
        {
            account = CloudConfiguration.GetStorageAccount("DataConnectionString");
        }

        public PollAnswer Retrieve(string facebookId)
        {
            var context = new PollDataContext(account) {MergeOption = MergeOption.NoTracking};

            var query = (from answer in context.PollAnswers
                         where answer.PartitionKey == facebookId.Encode()
                         select answer).AsTableServiceQuery();
            return query.Execute().SingleOrDefault();
        }

        public void Save(PollAnswer pollAnswer)
        {
            var context = new PollDataContext(account);
            try
            {
                context.AddObject(PollDataContext.PollAnswerTable, pollAnswer);
                context.SaveChanges();
                new PollResultRepository().Update(pollAnswer.Name, pollAnswer.Answer);
            }
            catch (InvalidOperationException ex)
            {
                Delete(pollAnswer);
                Trace.TraceError(ex.TraceInformation());
                throw;
            }
        }

        void Delete(PollAnswer pollAnswer)
        {
            if (pollAnswer == null)
                return;

            var answerToDelete = Retrieve(pollAnswer.Name);
            var context = new PollDataContext(account);
            context.DeleteObject(answerToDelete);
            context.SaveChanges();
        }
    }
}